package com.ruoyi.flowable.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.flowable.domain.ActRejectRecord;
import com.ruoyi.flowable.mapper.ActRejectRecordMapper;
import com.ruoyi.flowable.service.IActRejectRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ActRejectRecordServiceImpl implements IActRejectRecordService {

    @Autowired
    private ActRejectRecordMapper actRejectRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addRejectRecord(String procInstId, String taskId, String rejectReason) {
        ActRejectRecord record = new ActRejectRecord();
        record.setProcInstId(procInstId);
        record.setRejectStatus("rejected");
        record.setRejectReason(rejectReason);
        record.setRejectTime(new Date());
        record.setRejectTaskId(taskId);

        actRejectRecordMapper.insertActRejectRecord(record);
    }

    @Override
    public ActRejectRecord getRejectRecordByProcInstId(String procInstId) {
        return actRejectRecordMapper.selectByProcInstId(procInstId);
    }

    @Override
    public List<ActRejectRecord> selectByProcInstIds(List<String> procInstIds) {
        if (CollectionUtils.isEmpty(procInstIds)) {
            return new ArrayList<>();
        }
        return actRejectRecordMapper.selectByProcInstIds(procInstIds);
    }

    @Override
    public Map<String, ActRejectRecord> getRejectRecordMapByProcInstIds(List<String> procInstIds) {
        List<ActRejectRecord> records = selectByProcInstIds(procInstIds);
        return records.stream()
                .collect(Collectors.toMap(ActRejectRecord::getProcInstId, record -> record));
    }

    @Override
    public boolean isProcessRejected(String procInstId) {
        return getRejectRecordByProcInstId(procInstId) != null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRejectRecord(String procInstId) {
        actRejectRecordMapper.deleteByProcInstId(procInstId);
    }
}
